package com.dt.common.validation.definition;

import java.text.ParseException;
import java.text.SimpleDateFormat;

import com.dt.common.validation.annotation.DateStr;
import com.dt.common.validation.impl.DefaultValidationDefinition;
import com.dt.common.validation.itf.ConstraintValidation;
import com.dt.common.validation.itf.ValidationContext;

import lombok.Setter;

@Setter
public class DateStrDefinition extends DefaultValidationDefinition {

	private String format;

	public DateStrDefinition() {
		this.name = DateStr.class.getSimpleName();
	}

	@Override
	public ConstraintValidation buildValidation() {

		return new ConstraintValidation() {

			@Override
			public boolean isValid(ValidationContext context, Object objectValue, Object propertyValue) {
				if(propertyValue == null){
					return true;
				}
				if (propertyValue instanceof String) {
					try {
						final SimpleDateFormat sdf = new SimpleDateFormat(format);
						String dateStr = (String) propertyValue;

						sdf.parse(dateStr);
						return true;
					} catch (ParseException e) {
						// ignore exception
						return false;
					}
				}else{
					return false;
				}
			}

		};

	}

}
